package com.ksd1.notes;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.ksd1.notes.db.NoteDB;
import com.ksd1.notes.db.NoteDB.Note;
import com.ksd1.notes.util.NoteDirHelper;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;

public class NoteAdapter extends RecyclerView.Adapter<NoteAdapter.ViewHolder> implements View.OnClickListener{

    List<Note> mNoteList;
    Context mContext;
    private Dialog bottomDialog;
    private Dialog newDirDialog;
    private int mPos;//选择的日记项

    public NoteAdapter(List<Note> noteList) {
        mNoteList = noteList;
    }//浅拷贝

    @NonNull
    @Override
    public NoteAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        if (mContext == null) {
            mContext = parent.getContext();
        }
        View view = LayoutInflater.from(mContext).inflate(R.layout.note_item, parent, false);
        final ViewHolder holder = new ViewHolder(view);

        //在这里添加点击事件
        holder.item_box.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = holder.getAdapterPosition();
//                Toast.makeText(mContext, "" + position, Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(mContext, NoteActivity.class);
                intent.putExtra("NoteId", mNoteList.get(position).key);
                intent.putExtra("position", position);
                mContext.startActivity(intent);

            }
        });

        //被长按
        holder.item_box.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                final int position = holder.getAdapterPosition();
                PopupMenu popupMenu=new PopupMenu(mContext,v);//1.实例化PopupMenu
                ((Activity)mContext).getMenuInflater().inflate(R.menu.data_menu,popupMenu.getMenu());//2.加载Menu资源
                //3.为弹出菜单设置点击监听
                popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener(){

                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        switch (item.getItemId()){
                            case R.id.DataDelete:
                                NoteAdapter.this.delete(position);
                                return true;
                            case R.id.DataClear:
                                NoteAdapter.this.deleteAll();
                                return true;
                            case R.id.ChangeDir: //移动
                                mPos = position;
                                NoteAdapter.this.setDialog();
                            default:
                                return false;
                        }
                    }
                });
                popupMenu.show();//4.显示弹出菜单
                return true;
            }
        });

        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull NoteAdapter.ViewHolder holder, int position) {
        Note note = mNoteList.get(position);
        if (note != null) {
            holder.NoteDateText.setText(getDateStr(note.date));
            holder.NoteTitleText.setText(note.title);
        }
    }

    @Override
    public int getItemCount() {
        return mNoteList.size();
    }

    public static String getDateStr(long milliseconds) {
        return new SimpleDateFormat("yyyy年MM月dd日 EEEE HH点mm分", Locale.CHINA).format(milliseconds);
    }


    static class ViewHolder extends RecyclerView.ViewHolder {

        TextView NoteDateText;
        TextView NoteTitleText;
        LinearLayout item_box;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            NoteDateText = itemView.findViewById(R.id.NoteDateText);
            NoteTitleText = itemView.findViewById(R.id.NoteTitleText);
            item_box = itemView.findViewById(R.id.note_item_box);
        }
    }

    private void delete(final int pos){
        AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
        dialog.setTitle("删除警告");
        dialog.setMessage("删除过程不可撤销，您确定要删除吗？");
        dialog.setCancelable(false);
        dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                if(!NoteDB.getInstance().nremove(mNoteList.get(pos).key)){
                    Toast.makeText(mContext, "删除失败", Toast.LENGTH_SHORT).show();
                }
                mNoteList.remove(pos);
                MainActivity.noteAdapteradapter.notifyItemRemoved(pos);
            }
        });

        dialog.setNegativeButton("取消", new DialogInterface.OnClickListener(){

            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });

        dialog.show();

    }

    private void deleteAll(){
        AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
        dialog.setTitle("删除警告");
        dialog.setMessage("删除过程不可撤销，您确定要删除吗？");
        dialog.setCancelable(false);

        dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if(!NoteDB.getInstance().nremoveAllType(MainActivity.currentType)){
                    Toast.makeText(mContext, "删除失败", Toast.LENGTH_SHORT).show();
                }
                mNoteList.clear();
                MainActivity.noteAdapteradapter.notifyDataSetChanged();
            }
        });

        dialog.setNegativeButton("取消", new DialogInterface.OnClickListener(){

            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        dialog.show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.choose_default://默认
                NoteDirHelper.move(mPos, "未分类");
                closeDialog();
                break;
            case R.id.choose_study://学习
                NoteDirHelper.move(mPos, "学习");
                closeDialog();
                break;
            case R.id.choose_life://生活
                NoteDirHelper.move(mPos, "生活");
                closeDialog();
                break;
            case R.id.choose_new://新建文件夹
                setNewDirDialog();
                break;
            case R.id.new_cancel://取消
                closeNewDirDialog();
                break;
            case R.id.new_ok://ok
                NoteDirHelper.addDir(mContext);
                closeNewDirDialog();
                closeDialog();
                break;


        }
    }

//    底部弹出框
    private void setDialog() {
        bottomDialog = new Dialog(mContext, R.style.nBottomDialog);
        LinearLayout root = (LinearLayout) LayoutInflater.from(mContext).inflate(
                R.layout.bottom_dialog, null);
        //初始化视图
        root.findViewById(R.id.choose_default).setOnClickListener(this);
        root.findViewById(R.id.choose_life).setOnClickListener(this);
        root.findViewById(R.id.choose_new).setOnClickListener(this);
        root.findViewById(R.id.choose_study).setOnClickListener(this);


        bottomDialog.setContentView(root);
        Window dialogWindow = bottomDialog.getWindow();
        dialogWindow.setGravity(Gravity.BOTTOM);
        WindowManager.LayoutParams lp = dialogWindow.getAttributes(); // 获取对话框当前的参数值
        lp.x = 0; // 新位置X坐标
        lp.y = 0; // 新位置Y坐标
        lp.width = (int) mContext.getResources().getDisplayMetrics().widthPixels; // 宽度
        root.measure(0, 0);
        lp.height = root.getMeasuredHeight();

        lp.alpha = 9f; // 透明度
        dialogWindow.setAttributes(lp);
        bottomDialog.show();
    }

    private void setNewDirDialog(){
        newDirDialog = new Dialog(mContext, R.style.newDir);
        LinearLayout root = (LinearLayout) LayoutInflater.from(mContext).inflate(
                R.layout.bottom_newdir, null);
        //初始化视图
        //输入框
        final EditText new_dirname = root.findViewById(R.id.new_dirname);
        showKeyboard(new_dirname);

        //按钮
        root.findViewById(R.id.new_cancel).setOnClickListener(this);
        root.findViewById(R.id.new_ok).setOnClickListener(this);


        newDirDialog.setContentView(root);
        Window dialogWindow = newDirDialog.getWindow();
        dialogWindow.setGravity(Gravity.BOTTOM);

        //设置位置
        WindowManager.LayoutParams lp = dialogWindow.getAttributes(); // 获取对话框当前的参数值
        lp.x = 0; // 新位置X坐标
        lp.y = 0; // 新位置Y坐标
        lp.width = (int) mContext.getResources().getDisplayMetrics().widthPixels; // 宽度
        root.measure(0, 0);
        lp.height = root.getMeasuredHeight();
        lp.alpha = 9f; // 透明度
        dialogWindow.setAttributes(lp);
        newDirDialog.show();
    }

    public void showKeyboard(EditText editText) {
        if(editText!=null){
            editText.setFocusable(true);
            editText.setFocusableInTouchMode(true);
            editText.requestFocus();
            InputMethodManager inputManager = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.showSoftInput(editText, 0);
        }
    }

    private void closeDialog(){
        if(bottomDialog != null) bottomDialog.dismiss();
    }

    private void closeNewDirDialog(){
        if(newDirDialog != null) newDirDialog.dismiss();
    }

}
